import time
import sys
import time
import sys
import json
import io

# 设置sys.stdout的编码为UTF-8
sys.stdout.reconfigure(encoding='utf-8')
# 创建一个新的输出流，并设置编码为UTF-8
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 将 当且路径 添加到path中
sys.path.append(r'.')

from . import search_image_util
from DrissionPage._pages.chromium_tab import ChromiumTab


def zt_image(tab: ChromiumTab, desc_card, ztSearch):
    xiangqing_div = desc_card.ele('tag:span@@title=1:1主图')
    tupain_select_div = xiangqing_div.parent(2).next()
    # 多个添加图片
    tupian_divs = tupain_select_div.eles('tag:div@@text()=添加图片')
    if tupian_divs and len(tupian_divs) > 0:
        tupian_divs[0].click()
        time.sleep(2)

    # 按图片名升序
    search_image_util.set_image_sort(tab)
    search_image_util.search_image_input(tab, ztSearch, False, False)
    xiangqing_div.click()  # 失去焦点


def xq_image(tab: ChromiumTab, desc_card, xqSearch):
    xiangqing_div = desc_card.ele('tag:span@@title=详情描述')
    tupain_select_div = xiangqing_div.parent(2).next()
    tupian_div = tupain_select_div.ele('tag:div@@text()=图片')
    tupian_div.click()
    time.sleep(2)
    # 按图片名升序
    search_image_util.set_image_sort(tab)
    search_image_util.search_image_input(tab, xqSearch, False, False)
    xiangqing_div.click()  # 失去焦点


def update_zt_xq_image(tab: ChromiumTab, itemBean):
    search_image_util.click_titile_div(tab, '图文描述')
    desc_card = tab.ele('#desc-card')
    # 主图
    ztSearch = itemBean['ztSearch']
    zt_image(tab, desc_card, ztSearch)

    # 详情图
    xqSearch = itemBean['xqSearch']
    xq_image(tab, desc_card, xqSearch)
